var socket;
var userName;

function init(){
  var host = "ws://localhost:8080/chat";
  try{
    socket = new WebSocket(host);
//    log('WebSocket - status '+socket.readyState);
    //socket.onopen    = function(msg){ log("Welcome - status "+this.readyState); };
    socket.onmessage = function(msg){ log(msg.data); };
    socket.onclose   = function(msg){ log("Disconnected from server"); };
  }
  catch(ex){ log(ex); }
  $("msg").focus();
}

function send(){
  if (socket.readyState != 1) {
	  log("Could not connect to server, message wasn't delivered.");
	  return;
  }
  var txt,msg;
  txt = $("msg");
  msg = txt.value;
  if(!msg){ return; }
  txt.value="";
  txt.focus();
  try{ socket.send("msg||"+userName+"||||"+msg); } catch(ex){ log("Error: " + ex); }
}
function quit(){
  log("Goodbye!");
  socket.close();
  socket=null;
}

function login() {
	nameField = $("name");
	name = nameField.value;
	userName = name;
	msg = "setname||||||"+name;
	try{ socket.send(msg); } catch(ex){ log("Error: " + ex); }
	$("chooseName").style.display = "none";
	$("chatWindow").style.display = "block";
}

//Utilities
function $(id){ return document.getElementById(id); }
function log(msg){ $("log").innerHTML+="<br>"+msg; }
function onkey(event){ if(event.keyCode==13){ send(); } }
